package com.chuanghai.light.exceptionhandle.handle;

import com.chuanghai.light.exceptionhandle.CommonException;
import com.chuanghai.light.exceptionhandle.emum.CommonErrorEmum;
import com.chuanghai.light.response.CommonReturnType;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * 全局异常处理
 */
@ControllerAdvice
public class ExceptionHandle {

    // 定义exceptionHandle解决未被controller层吸收的Exception
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public @ResponseBody
    CommonReturnType handleException(HttpServletRequest request, Exception e){
        e.printStackTrace();
        e.getMessage();
        HashMap<String, Object> responseData = new HashMap<>();
        if (e instanceof CommonException){
            CommonException b = (CommonException)e;
            responseData.put("errCode",b.getErrorCode());
            responseData.put("errMsg",b.getErrorMsg());
        } else if (e instanceof MissingServletRequestParameterException) {
            responseData.put("errCode", CommonErrorEmum.PARAMETER_VALIDATION_ERROR.getErrorCode());
            responseData.put("errMsg", CommonErrorEmum.PARAMETER_VALIDATION_ERROR.getErrorMsg());
        } else if (e instanceof HttpRequestMethodNotSupportedException) {
            responseData.put("errCode", CommonErrorEmum.REQUEST_WAY_ERROR.getErrorCode());
            responseData.put("errMsg", CommonErrorEmum.REQUEST_WAY_ERROR.getErrorMsg());
        } else {
            responseData.put("errCode", CommonErrorEmum.UNKNOW_CODE.getErrorCode());
            responseData.put("errMsg",CommonErrorEmum.UNKNOW_CODE.getErrorMsg());
        }
        return CommonReturnType.create("fail",responseData);
    }
}
